import { useEffect, useState, useRef } from 'react';
import { Button, Table, Popover, Image } from 'antd';
import { useNavigate } from 'react-router-dom';
import FooterToolbar from '@/components/FooterToolbar';
import CommonPage from '@/components/CommonPagination';
import CommonLoading from '@/components/CommonLoading';
import CommonTableSpan from '@/components/CommonTableSpan';
import { formatZjfImg, commonExportForPage, formatAmount } from '@/utils/utils.jsx';
import moment from 'moment';
import { getCheckBillTableListOp } from '../../service';
import styles from './index.module.less';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const initPagination = {
  current: 1,
  total: 0,
  pageSize: 20,
  pageSizeOptions: ['20', '50', '100', '200', '500']
}

const billTypeMap = {
  0:'门店拿货', 
  1:'退货退款', 
  2:'直发订单', 
  3:'采购订单', 
  4:'优惠金额'
}

export default ({ query, current }) => {

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState(null);
	const navigate = useNavigate();
  const stageParams = useRef({});

  const { type, contractNo = 'NO6120230406163937733', period, } = current;

  useEffect(()=>{
    if(query){
      setPagination({
        ...(pagination || initPagination),
        current:1
      })
    }else{
      setData([]);
    }
  } ,[query])

  useEffect(()=>{
    if(pagination){
      getTableListFunc();
    }
  } ,[pagination])

  const getTableListFunc = async () => {
    setLoading(true);
    const params = {...query};
    if(params.time){
      if(params.timeType == 1){
        params.payTimeStart = moment(query.time[0]).format(dateFormat);
        params.payTimeEnd = moment(query.time[1]).format(dateFormat);
      }else if(params.timeType == 2){
        params.relianceTimeStart = moment(query.time[0]).format(dateFormat);
        params.relianceTimeEnd = moment(query.time[1]).format(dateFormat);
      }
    }
    params.time = undefined;
    params.timeType = undefined;
    params.contractNo = contractNo;
    type != 2 && (params.period = period);
    stageParams.current = params;//以供导出备用
    const { data, success } = await getCheckBillTableListOp({
      ...params,
      current: pagination.current,
      size: pagination.pageSize,
    });
    setLoading(false);
    if(success){
      const { records = [], total } = data || {};
      pagination.total = total;
      setData(records)
    }else{
      pagination.total = 0;
      setData([]);
    }
  }


  //渲染跳转去页面去订单处理页面的span
  const renderJumptOrderHandle = (orderSn) => {
    return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick('/views/order/list', orderSn)}>{orderSn}</span>
  }

  //公共跳转逻辑
  const publicHandleClick = (pathname, orderSn, erpOrderSrc) => {
    let timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      navigate(pathname, { state: {orderSn, erpOrderSrc }});
    },200)
  }
  
  const frontColumns= [
    {
      title: '流水单号',
      dataIndex: 'tradeNo',
      key: 'tradeNo',
      width: 150,
    },
    {
      title: "关联单号",
      dataIndex: "orderSn",
      key: "orderSn",
      width: 145,
      render:(text, { transType, tradeNo })=>{
        const noJumptarr = [1, 2, 3, 6, 7, 10, 11, 14, 15, 16, 17, 18 ],
              jumptOrderHandleArr = [4, 5, 8, 12, 13, 21, 22, 23, 25, 27, 33, 34, 35, 37]
        if(noJumptarr.includes(transType)){
          return <span>{text}</span>
        } else if(tradeNo.startsWith('S')) {
            return renderJumptOrderHandle(text);
        }
        else if(jumptOrderHandleArr.includes(transType)){//订单反审核
          return renderJumptOrderHandle(text)
        } else if (transType == 28 || transType == 29 || transType == 30) { //采购订单
            return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=> {navigate("/views/purchase/PurchaseOrder?purchaseOrderNos=" + text);}
              }>{text}</span>
        } else{
          return <span>{text}</span>
        }
      }
    },
    {
      title: "支付类型",
      dataIndex: "billType",
      key: "billType",
      width: 80,
      render: text => billTypeMap[text]
    },
    {
      title: "支付时间",
      dataIndex: "payTime",
      key: "payTime",
      width: 120
    },
  ]

  const lastColumns = [
    {
      title: "商品名称",
      dataIndex: "goodsName",
      key: "goodsName",
      width: 180,
      render:(_, { billType, goodsImage, goodsName, storeId, storeName, goodsSpec, goodsCode, transType })=>{
        if(billType == 4){//优惠金额不展示
          return null;
        }
        if(transType == 20) {
            return goodsName;
        }
        const imgUrl = formatZjfImg(goodsImage,storeId);
        return (<div style={{display:'flex'}}>
          <div className={styles.imageWrapper}>
            <Popover content={<img src={imgUrl} width={320} />}>
              <Image src={imgUrl} width={48} />
            </Popover>
          </div>
          <div style={{flex:1}}>
            <Popover
              content={
                <div className="custom-ant-popver-content">
                  <div>【{storeName}】{goodsName}</div>
                  <div>{goodsSpec}</div>
                </div>
              }
            >
              <span>
                <CommonTableSpan
                  sku={goodsName}
                  spu={goodsSpec}
                  storeName={storeName}
                />
              </span>
            </Popover>
            商品编码：{ goodsCode }
          </div>
        </div>)
      }
    },
    {
      title: "商品数量",
      dataIndex: "goodsNum",
      key: "goodsNum",
      width: 80
    },
    {
      title: "收支金额",
      dataIndex: "showAmount",
      key: "showAmount",
      width: 90,
      render: (_, { showAmount, payType }) => <span className={ payType === 0 ? "common-color10" : "common-color9"}>{showAmount}</span>
    },
  ]

  const renderColumns = () => {
    if(type == 1){
      return [...frontColumns,...lastColumns];
    }else{
      return [
        ...frontColumns,
        {
          title: "入账时间",
          dataIndex: "relianceTime",
          key: "relianceTime",
          width: 120
        },
        ...lastColumns];
    }
  }

  const commonTableProps = {
    data,
    bordered: true,
    pagination: false,
    columns:renderColumns(),
    dataSource: data,
    rowKey: 'id',
    scroll:{y: 480},
    summary: (pageData) => {
     let totalNum = 0, totalAmount = 0;
     pageData.map(item=>{
      totalNum += item.goodsNum;
      totalAmount += item.amount;
     })
     totalAmount = (totalAmount/100).toFixed(2);
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            <Table.Summary.Cell index={0}>总计</Table.Summary.Cell>
            <Table.Summary.Cell index={0}></Table.Summary.Cell>
            <Table.Summary.Cell index={0}></Table.Summary.Cell>
            <Table.Summary.Cell index={0}></Table.Summary.Cell>
            {type != 1 && <Table.Summary.Cell index={0}></Table.Summary.Cell>}
            <Table.Summary.Cell index={0}>{totalNum}</Table.Summary.Cell>
            <Table.Summary.Cell index={0}>{totalAmount ? formatAmount(totalAmount) : '0.00'}</Table.Summary.Cell>
          </Table.Summary.Row>
        </Table.Summary>
      )
    }
  }

  // 分页组件数据
  const pageProps = {
    pagination,
    handleChange(current, pageSize) {
      setPagination({
        ...pagination,
        current,
        pageSize,
      });
    },
  };
  
  const onExport = () => {
    commonExportForPage({
      total:pagination.total, 
      params: stageParams.current,
      url:'/zjf-pays/credit/reconciliation/export',
      name:'账期对账'
    })
  }

  return (<>
    <Button onClick={onExport}  shape='round' size='default' style={{marginBottom:'8px'}}>表格导出</Button>
    <Table {...commonTableProps} />
    <FooterToolbar>
      <CommonPage {...pageProps} />
    </FooterToolbar>
    <CommonLoading loading={loading} />
  </>)
}